package com.tan.lbs.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.tan.lbs.activity.R;
import com.tan.lbs.dao.ItemDAO;
import com.tan.lbs.dao.NPCDAO;
import com.tan.lbs.dao.QuestDAO;
import com.tan.lbs.dao.impl.ItemDAOImpl;
import com.tan.lbs.dao.impl.NPCDAOImpl;
import com.tan.lbs.dao.impl.QuestDAOImpl;
import com.tan.lbs.entity.GameRuleManager;
import com.tan.lbs.entity.Item;
import com.tan.lbs.entity.NPC;
import com.tan.lbs.entity.Quest;
import com.tan.lbs.entity.Trigger;
import com.tan.lbs.overlay.GameElementOverlayItem;
import com.tan.lbs.overlay.GameOverlay;
import com.tan.lbs.util.Constants;
import com.tan.lbs.util.LatLngPoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

public class MapTabActivity extends MapActivity {

	private MapController myMapController;
	private boolean isQuestOn = true;
	private LocationManager locationManager;
	private PlayerLocationListener playerLocationListener;
	private GameOverlay questOverlay;
	private GameOverlay npcOverlay;
	private GameOverlay itemOverlay;
	private GameOverlay playerOverlay;
	private MapView mapView;
	private Location playerLocation;
	private String gameID;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.maptab);
		gameID = getSharedPreferences(Constants.PREFS_NAME, 0).getString("currentGameID", "");
		// init test data
		LatLngPoint centerGeoPoint = new LatLngPoint(53.4, -6.3);
		playerLocation = new Location("");
		playerLocation.setLatitude(53.4);
		playerLocation.setLongitude(-6.3);
		// end init test

		mapView = (MapView) findViewById(R.id.mapView);
		myMapController = mapView.getController();
		mapView.setBuiltInZoomControls(true);
		List<Overlay> mapOverlays = mapView.getOverlays();
		Drawable npcDrawable = getResources().getDrawable(R.drawable.npc);
		Drawable questDrawable = getResources().getDrawable(R.drawable.quest);
		Drawable itemDrawable = getResources().getDrawable(R.drawable.item);
		Drawable playerDrawable = getResources().getDrawable(
				R.drawable.user_male);
		itemOverlay = new GameOverlay(itemDrawable, this, playerLocation);
		itemOverlay.setMapView(mapView);
		npcOverlay = new GameOverlay(npcDrawable, this, playerLocation);
		questOverlay = new GameOverlay(questDrawable, this, playerLocation);
		playerOverlay = new GameOverlay(playerDrawable, this, playerLocation);
		NPCDAO npcDAO = new NPCDAOImpl(this);
		ItemDAO itemDAO = new ItemDAOImpl(this);
		QuestDAO questDAO = new QuestDAOImpl(this);
		String gameID = getSharedPreferences(Constants.PREFS_NAME, 0)
				.getString("currentGameID", "");
		List<NPC> npcs = npcDAO.retrieveNPCs(gameID);
		List<Quest> quests = questDAO.retreiveQuests(gameID);
		List<Item> items = itemDAO.retreiveItems(gameID);
		for (NPC npc : npcs) {
			LatLngPoint point = new LatLngPoint(npc.getLat(), npc.getLng());
			GameElementOverlayItem npcOverlayitem = new GameElementOverlayItem(
					npc, GameElementOverlayItem.NPC_ELE, npc.getNpcID(), point,
					npc.getName(), npc.getGreeting());
			npcOverlay.addOverlay(npcOverlayitem);
		}
		
		for (Item item : items) {
			if(!item.getStatus().equals(Item.PICKED)) {
				LatLngPoint point = new LatLngPoint(item.getLat(), item.getLng());
				GameElementOverlayItem itemOverlayitem = new GameElementOverlayItem(
						item, GameElementOverlayItem.ITEM_ELE, item.getItemID(), point,
						item.getTitle(), "");
				itemOverlay.addOverlay(itemOverlayitem);
			}
		}

		for (Quest quest : quests) {
			if(!quest.getStatus().equals(Quest.COMPLETE_STATUS)) {
			LatLngPoint point = new LatLngPoint(quest.getLat(), quest.getLng());
			GameElementOverlayItem questOverlayitem = new GameElementOverlayItem(
					quest, GameElementOverlayItem.QUEST_ELE, quest.getQuestID(),
					point, quest.getTitle(), "");
			questOverlay.addOverlay(questOverlayitem);
			}
		}

		GameElementOverlayItem playerOverLayItem = new GameElementOverlayItem(
				null, GameElementOverlayItem.PLAYER_ELE, null, centerGeoPoint,
				"user", "user");

		playerOverlay.addOverlay(playerOverLayItem);

		mapOverlays.add(npcOverlay);
		mapOverlays.add(questOverlay);
		mapOverlays.add(itemOverlay);
		mapOverlays.add(playerOverlay);

		myMapController.setCenter(centerGeoPoint);
		myMapController.setZoom(12);

	}

	@Override
	public void onResume() {
		super.onResume();
		if (isQuestOn) {
			setUpLocationConfiguration();
		}
		
	}

	private void setUpLocationConfiguration() {
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

		if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
				|| !locationManager
						.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
			createGpsDisabledAlert();
		}

		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		String provider = locationManager.getBestProvider(criteria, true);
		locationManager.getAllProviders();
		playerLocationListener = new PlayerLocationListener();
		// emualator requires GPS!
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
				0, playerLocationListener);
		
	}

	private void stopLocationUpdate() {
		if (playerLocationListener != null) {
			locationManager.removeUpdates(playerLocationListener);
		}
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	private void createGpsDisabledAlert() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(
				"Your GPS and network is disabled! Would you like to enable them?")
				.setCancelable(false)
				.setPositiveButton("Enable them",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								Intent gpsOptionsIntent = new Intent(
										android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
								startActivity(gpsOptionsIntent);
							}
						});
		builder.setNegativeButton("Back",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	class PlayerLocationListener implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
			playerLocation.setLatitude(location.getLatitude());
			playerLocation.setLongitude(location.getLongitude());
			playerOverlay.removeAllOverlay();
			GameElementOverlayItem playerOverLayItem = new GameElementOverlayItem(
					null, GameElementOverlayItem.PLAYER_ELE, null,
					new LatLngPoint(playerLocation.getLatitude(),
							playerLocation.getLongitude()), "user", "user");
			playerOverlay.addOverlay(playerOverLayItem);
			mapView.invalidate();
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}

	}

}
